package be.fomp.jeve.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import junit.framework.TestCase;

/**
 * This is the super class for the connector tests.
 * It contains an api key and related information that will be used to test
 * the connectors.
 * 
 * Uses a '.testApiData' configuration file. If this file does not already exist, then
 * the first failure should contain the path where this file should be.
 * 
 * @author Candle
 *
 */
public abstract class APIData extends TestCase {
	int userID;
	String apiKey;
	int characterID;
	
	public APIData() {
		String usageString = "\nThis file should have three elements: " +
		"\n\tuserID=(number)" +
		"\n\tapiKey=(base64 string)" +
		"\n\tcharacterID=(number)";
		
		Properties testConfig = new Properties();
		File testConfigFile = new File(".testApiData"); // TODO put this file in a sensible place like the user's home directory.
		
		if (!testConfigFile.exists()) {
			fail("Failed to find the test configuration file at "
					+ testConfigFile.getAbsolutePath()
					+ usageString);
		}
		
		try {
			testConfig.load(new FileInputStream(testConfigFile));
		} catch (IOException ioe) {
			fail("Unknown IO exception when loading the configuration: " + ioe);
		}
		
		// All the configuration options should be in the properties now, if not, I need to 'fail' more!
		String userIDTemp = testConfig.getProperty("userID");
		if (userIDTemp == null) {
			// there was no property set; fail again.
			fail("There was no userID in the configuration." + usageString);
		} else {
			try {
				userID = Integer.parseInt(userIDTemp);
			} catch (NumberFormatException nfe) {
				fail("Unable to parse the userID value as a number." + nfe);
				throw nfe;
			}
		}
		
		String apiKeyTemp = testConfig.getProperty("apiKey");
		if (apiKeyTemp == null) {
			// no apiKey set.
			fail("There was no apiKey in the configuration." + usageString);
		} else {
			// check the string is of the expected form
			if (apiKeyTemp.matches("[a-zA-Z0-9]{64}")) {
				// correct form
				apiKey = apiKeyTemp;
			} else {
				// failed somewhere...!
				fail("The apiKey value was not in the expected form:" +
						" it must contain 64 characters," +
						" each of which is a an upper or lower case letter or a digit." +
						usageString);
			}
		}
		
		// and finally... the characterID
		// TODO ? use the api to convert a character NAME to a character ID??
		String characterIDTemp = testConfig.getProperty("characterID");
		if (characterIDTemp == null) {
			// no characterID
			fail("There was no character ID in the configuration." + usageString);
		} else {
			try {
				characterID = Integer.parseInt(characterIDTemp);
			} catch (NumberFormatException nfe) {
				fail("Unable to parse the characterID value as a number." + nfe);
				throw nfe;
			}
		}
		
	}
}
